/**
 * Copyright (c) 2016-2023, Michael Yang 杨福海 (fuhai999@gmail.com).
 * <p>
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl-3.0.txt
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.jpress.web.admin;

import com.jfinal.aop.Inject;
import io.jboot.web.controller.annotation.RequestMapping;
import io.jboot.web.validate.EmptyValidate;
import io.jboot.web.validate.Form;
import io.jpress.JPressConsts;
import io.jpress.core.menu.annotation.AdminMenu;
import io.jpress.model.Permission;
import io.jpress.model.PermissionGroup;
import io.jpress.model.Role;
import io.jpress.model.base.BasePermission;
import io.jpress.model.base.BasePermissionGroup;
import io.jpress.permission.PermissionTypes;
import io.jpress.permission.annotation.NeedPermission;
import io.jpress.permission.annotation.PermissionDef;
import io.jpress.service.PermissionGroupService;
import io.jpress.service.PermissionService;
import io.jpress.service.RoleService;
import io.jpress.web.AdminPermissionGroups;
import io.jpress.web.base.AdminControllerBase;

import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * @author Michael Yang 杨福海 （fuhai999@gmail.com）
 * @version V1.0
 * @Title: 用户角色相关的 Controller
 */
@RequestMapping(value = "/admin/user/role", viewPath = JPressConsts.DEFAULT_ADMIN_VIEW)
public class _UserRoleController extends AdminControllerBase {


    @Inject
    private RoleService roleService;

    @Inject
    private PermissionService permissionService;

    @Inject
    private PermissionGroupService permissionGroupService;


    /**
     * 角色信息列表
     */
    @PermissionDef(title = "查看角色列表", groupId = AdminPermissionGroups.USER)
    @AdminMenu(text = "角色", groupId = JPressConsts.SYSTEM_MENU_USER, order = 9)
    public void index() {
        List<Role> roles = roleService.findAll();
        setAttr("roles", roles);
        render("user/role.html");
    }


    /**
     * 某个角色的权限信息
     */
    @PermissionDef(title = "查看角色权限", groupId = AdminPermissionGroups.USER)
    public void permissions() {
        Long id = getParaToLong();
        if (id == null) {
            renderError(404);
            return;
        }

        Role role = roleService.findById(id);
        setAttr("role", role);

        Integer type = getParaToInt("type", PermissionTypes.MENU);
        List<Permission> permissions = permissionService.findListByType(type);
        List<PermissionGroup> permissionGroups = permissionGroupService.findListByType(type);


        List<Permission> rolePermissions = permissionService.findPermissionListByRoleId(role.getId());

        if (permissionGroups != null && !permissionGroups.isEmpty() && permissions != null && !permissions.isEmpty()) {

            permissions.sort(Comparator.comparing(BasePermission::getId));
            permissionGroups.sort(Comparator.comparingInt(BasePermissionGroup::getSortNo));


            for (Permission permission : permissions) {
                boolean roleHasPermission = (rolePermissions != null && rolePermissions.contains(permission));
                if (roleHasPermission) {
                    permission.put("checked", true);
                }

                for (PermissionGroup permissionGroup : permissionGroups) {
                    if (Objects.equals(permission.getGroupId(), permissionGroup.getId())) {
                        permissionGroup.addPermission(permission);
                        if (roleHasPermission) {
                            permissionGroup.put("checked", true);
                        }
                    }
                }
            }
        }

        setAttr("groups", permissionGroups);
        setAttr("type", type);

        render("user/role_permissions.html");
    }


    /**
     * 编辑角色信息页面
     */
    @PermissionDef(title = "编辑角色信息", groupId = AdminPermissionGroups.USER)
    public void edit() {
        Long id = getParaToLong();
        if (id != null) {
            setAttr("role", roleService.findById(id));
        }
        render("user/role_edit.html");
    }


    /**
     * 保存角色信息
     */
    @NeedPermission("./edit")
    @EmptyValidate({@Form(name = "role.name", message = "角色名称不能为空")})
    public void doSave() {
        Role role = getBean(Role.class);
        if (getParaToBoolean("issuper", false)) {
            role.setFlag(Role.ADMIN_FLAG);
        } else {
            role.setFlag(null);
        }

        Object id = roleService.saveOrUpdate(role);
        renderOkJson("id", id);
    }

    /**
     * 删除角色
     */
    @PermissionDef(title = "删除角色信息", groupId = AdminPermissionGroups.USER)
    public void doDel() {
        roleService.deleteById(getIdPara());
        renderOkJson();
    }


    /**
     * 批量删除角色
     */
    @PermissionDef(title = "批量删除角色信息", groupId = AdminPermissionGroups.USER)
    @EmptyValidate(@Form(name = "ids"))
    public void doDelByIds() {
        Set<String> idsSet = getParaSet("ids");
        render(roleService.deleteByIds(idsSet.toArray()) ? OK : FAIL);
    }


}
